<template>
  <div class="login">
    <img
      :src="logo"
      alt="logo"
      style="width: 200px; display: block; margin: 0 auto"
    />
    <van-form class="login-form" @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="用户名"
          label="用户名："
          placeholder="请输入用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="密码"
          label="密码："
          placeholder="请输入密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div class="register" @click="goReg">
        <span>没有账号？立即注册</span>
      </div>
      <div style="margin: 16px">
        <van-button
          round
          color="#1ba784"
          block
          type="primary"
          native-type="submit"
        >
          登陆
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { login } from '@/api/modules/user'
import { showSuccessToast, showFailToast } from 'vant'

import logo from '@/assets/logo.svg'
const router = useRouter()

const username = ref('')
const password = ref('')
const onSubmit = async (values) => {
  try {
    const { data } = await login({
      username: username.value,
      password: password.value
    })

    new Promise((resolve, reject) => {
      localStorage.setItem('token', data.data.token)
      showSuccessToast('登陆成功')
      resolve()
    }).then(() => {
      router.push('/mine')
    })
  } catch (error) {
    // console.log(error)
    if (error.response.data.code === '10005') {
      // console.log('用户名或密码错误')
      showFailToast('用户名或密码错误')
    }
  }
}

const goReg = () => {
  // console.log('goReg')
  router.push('/register')
}
</script>

<style lang="less" scoped>
.login {
  background-color: #f5f5f5;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.login-form {
  width: 80%;
  padding: 20px;
}
.register {
  text-align: right;
  margin: 10px 0;
  padding: 10px 20px;
  font-size: 0.8rem;
  text-decoration: underline;
}
</style>
